//
//  AESOutputStream.m
//  NSStreamTest
//
//  Created by comeontom on 14/8/22.
//  Copyright (c) 2014年 comeontom. All rights reserved.
//

#import "AESOutputStream.h"
#import "EncryptedFileURLProtocol.h"
#import "NSDataEncrypt.h"

@interface AESOutputStream()
@property(nonatomic,strong)NSOutputStream *outputStream;
@end

@implementation AESOutputStream

-(instancetype)initWithOutputStream:(NSOutputStream *)delegate{
    if (self = [super init]) {
        self.outputStream = delegate;
    }
    return self;
}

//+ (instancetype)sharedInstance:(NSOutputStream *)delegate
//{
//    static AESOutputStream *sharedAESOutputStream = nil;
//    static dispatch_once_t onceToken;
//    dispatch_once(&onceToken, ^{
//        sharedAESOutputStream = [[AESOutputStream alloc] init];
//    });
//    sharedAESOutputStream->_outputStream = delegate;
//    return sharedAESOutputStream;
//}
-(void)open{
//    NSLog(@"AESOutputStream open");
    [self.outputStream open];
}
- (NSInteger)write:(const uint8_t *)buffer maxLength:(NSUInteger)len{
//    NSLog(@"AESOutputStream write:maxLength:");
    NSData *data = [NSData dataWithBytes:(const void *)buffer length:len];
    
    NSData *aesData = [data aesEncrypt:[[EncryptedFileURLProtocol key]md5Data]];
    NSUInteger dataLen = [aesData length];
    
    NSInteger integer = [self.outputStream write:[aesData bytes] maxLength:dataLen];
    
    return integer;
}
-(void)close{
//    NSLog(@"AESOutputStream close");
    [self.outputStream close];
}
@end
